package com.sskj.fca.ui.fragment;

import android.Manifest;
import android.graphics.Bitmap;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.bulong.rudeness.RudenessScreenHelper;
import com.chad.library.adapter.base.entity.MultiItemEntity;
import com.sskj.common.base.App;
import com.sskj.common.box.decoration.DividerLineItemDecoration;
import com.sskj.common.rxbus2.RxBus;
import com.sskj.common.util.ClickUtil;
import com.sskj.common.util.ImgUtil;
import com.sskj.common.util.PermissionTipUtil;
import com.sskj.common.util.ToastUtil;
import com.sskj.lib.RConfig;
import com.sskj.lib.base.BaseFragment;
import com.sskj.lib.bean.UserBean;
import com.sskj.lib.util.CopyUtil;
import com.sskj.lib.util.QRCodeUtil;
import com.sskj.fca.R;
import com.sskj.fca.bean.CommonBean;
import com.sskj.fca.bean.LinkBean;
import com.sskj.fca.bean.rxbus.MainChangeTabBean;
import com.sskj.fca.presenter.TheAgentPresenter;
import com.sskj.fca.ui.adapter.ExpandAdapter;
import com.sskj.fca.ui.adapter.Level0Item;
import com.sskj.fca.ui.adapter.Level1Item;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

/**
 * Created by Q-Kang on 2019/1/21.
 */
@Route(path = RConfig.APP_FRAGMENT_THE_AGENT)//全民代理
public class TheAgentFragment extends BaseFragment<TheAgentPresenter> {
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.btn_agent_system)
    Button btnAgentSystem;
    @BindView(R.id.btn_agent_fail)
    Button btn_agent_fail;
    @BindView(R.id.btn_apply_agent)
    Button btn_apply_agent;
    @BindView(R.id.btn_connect_us)
    Button btn_connect_us;//联系我们
    @BindView(R.id.btn_read_agent_rule)
    Button btn_read_agent_rule;//阅读代理条款
    @BindView(R.id.tv_agent_plan)
    TextView tv_agent_plan;
    @BindView(R.id.tv_fail_reason)
    TextView tv_fail_reason;
    @BindView(R.id.tv_save_agent_card)
    TextView tv_save_agent_card;//保存代理卡
    @BindView(R.id.tv_copy_agent_url)
    TextView tv_copy_agent_url;//复制代理链接
    @BindView(R.id.ll_agent_plan)
    LinearLayout ll_agent_plan;
    @BindView(R.id.ll_agent_success)
    LinearLayout ll_agent_success;
    @BindView(R.id.ll_agent_fail)
    LinearLayout ll_agent_fail;
    @BindView(R.id.ll_agent_wait)
    LinearLayout ll_agent_wait;
    @BindView(R.id.ll_apply_agent)
    LinearLayout ll_apply_agent;
    private ExpandAdapter expandAdapter;
    private ArrayList<MultiItemEntity> list = new ArrayList<>();
    private Bitmap mBitmap;
    private String spread;

    @Override
    protected int getLayoutId() {
        return R.layout.app_fragment_agent;
    }

    @Override
    protected TheAgentPresenter getPresenter() {
        return new TheAgentPresenter();
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        mPresenter.getUserInfo();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            if (ll_agent_plan.getVisibility() == View.GONE) {
                ll_agent_plan.setVisibility(View.VISIBLE);
            }
        }
    }

    @Override
    public void initView() {
        super.initView();
        mPresenter.getUserInfo();
        mPresenter.getCommonData();
        ClickUtil.click(tv_agent_plan, () -> {
            if (ll_agent_plan.getVisibility() == View.GONE) {
                ll_agent_plan.setVisibility(View.VISIBLE);
            } else if (ll_agent_plan.getVisibility() == View.VISIBLE) {
                ll_agent_plan.setVisibility(View.GONE);
            }
        });
        ClickUtil.click(btnAgentSystem, () ->
                ToastUtil.showShort("敬请期待")
        );
        ClickUtil.click(tv_copy_agent_url, () -> {
            if (TextUtils.isEmpty(spread)) {
                return;
            }
            CopyUtil.copy(spread);
        });
        ClickUtil.click(tv_save_agent_card, () -> new RxPermissions(getActivity()).request(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .subscribe(isGrant -> {
                    if (isGrant) {
                        ImgUtil.saveImageToGallery(getActivity(), mBitmap);
                    } else {
                        PermissionTipUtil.tip(getActivity(), "存储");
                    }
                }));
        ClickUtil.click(btn_connect_us, new ClickUtil.Click() {
            @Override
            public void click() {
                RxBus.getDefault().post(new MainChangeTabBean(7));
            }
        });
        ClickUtil.click(btn_read_agent_rule, () -> {
            if (list.size() > 1) {
                expandAdapter.expand(0);
            }
        });
        ClickUtil.click(btn_agent_fail, () -> ARouter.getInstance().build(RConfig.APP_APPLY_AGENT).navigation());
        ClickUtil.click(btn_apply_agent, () -> ARouter.getInstance().build(RConfig.APP_APPLY_AGENT).navigation());
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        recyclerView.addItemDecoration(new DividerLineItemDecoration(getActivity())
                .setPaintWidth((int) RudenessScreenHelper.pt2px(App.INSTANCE, 40))
                .setDividerColor(ContextCompat.getColor(App.INSTANCE, R.color.transparent))
        );
        expandAdapter = new ExpandAdapter(list);
        expandAdapter.closeLoadAnimation();
        recyclerView.setAdapter(expandAdapter);
    }

    public void updataUI(CommonBean commonBean) {
        list.clear();
        Level0Item level0Item = new Level0Item("代理条款");
        Level0Item level0Item1 = new Level0Item("佣金规则");
        CommonBean.ProxyInfoBean proxy_info = commonBean.getProxy_info();
        List<CommonBean.ProxyInfoBean.TermsBean> terms = proxy_info.getTerms();
        for (int i = 0; i < terms.size(); i++) {
            Level1Item level1Item = new Level1Item(terms.get(i).getTitle(), terms.get(i).getContent().replaceAll("\\|", "\n"));
            level0Item.addSubItem(level1Item);
        }
        List<CommonBean.ProxyInfoBean.CommissionBean> commission = proxy_info.getCommission();
        for (int i = 0; i < commission.size(); i++) {
            Level1Item level1Item = new Level1Item(commission.get(i).getTitle(), commission.get(i).getContent().replaceAll("\\|", "\n"));
            level0Item1.addSubItem(level1Item);
        }
        list.add(level0Item);
        list.add(level0Item1);
        expandAdapter.notifyDataSetChanged();

    }

    public void updateUser(UserBean userBean) {
        if (userBean == null) {
            return;
        }
        ll_agent_success.setVisibility(View.GONE);
        ll_agent_wait.setVisibility(View.GONE);
        ll_agent_fail.setVisibility(View.GONE);
        ll_apply_agent.setVisibility(View.GONE);
        if (userBean.getIs_daili().equals("0")) {//申请代理
            if (userBean.getApply_info() == null) {
                //未申请
                ll_apply_agent.setVisibility(View.VISIBLE);
                return;
            }
            switch (userBean.getApply_info().getStatus()) {
                case "1"://审核中
                    ll_agent_wait.setVisibility(View.VISIBLE);
                    break;
                case "3"://申请失败
                    ll_agent_fail.setVisibility(View.VISIBLE);
                    tv_fail_reason.setText("失败原因：" + userBean.getApply_info().getMsg());
                    break;
            }
            return;
        } else {
            //申请成功
            ll_agent_success.setVisibility(View.VISIBLE);
        }
        //如果申请成功，调取推广信息接口
        if (ll_agent_success.getVisibility() == View.VISIBLE) {
            mPresenter.getLinkData();
        }
    }

    public void updataUI(LinkBean linkBean) {
        if (linkBean == null) {
            return;
        }
        spread = linkBean.getUrl();
        QRCodeUtil.createImage(linkBean.getQrc(), (int) RudenessScreenHelper.pt2px(getActivity(), 230), new QRCodeUtil.OnEncodeQRCodeCallback() {
            @Override
            public void onAnalyzeSuccess(Bitmap bitmap) {
                mBitmap = bitmap;
            }

            @Override
            public void onAnalyzeFailed() {

            }
        });
    }

}
